import axios from "axios";
import { MessageBox, Message } from "element-ui";
import router from '@/router';
import { TOKEN_HEADER_NAME } from "@/config/setting";
import { getToken, setToken, removeToken } from "@/utils/auth";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000, // request timeout
});

/* 跳转到登录页面 */
const goLogin = function (from) {
  removeToken();
  router.push({
    path: "/login",
    query: from ? { from } : undefined,
  });
};

/* 添加请求拦截器 */
service.interceptors.request.use(
  (config) => {
    // 添加token到header
    const token = getToken();
    if (token && config.headers) {
      config.headers[TOKEN_HEADER_NAME] = 'Bearer ' + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/* 添加响应拦截器 */
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 1) {
      Message({
        message: res.message || "Error",
        type: "error",
        duration: 5 * 1000,
      });
    }
    // token自动续期
    const token = response.headers[TOKEN_HEADER_NAME];
    if (token) {
      setToken(token);
    }
    return res;
  },
  (error) => {
    if (error.response.status === 400) {
      return Promise.reject(
        new Error(error.response.data.responseStatus.message)
      );
    } else {
      if (error.response.status === 401) {
        const currentPath = router.currentRoute.path;
        MessageBox.alert("登录状态已过期, 请退出重新登录!", "系统提示", {
          confirmButtonText: "重新登录",
          callback: (action) => {
            if (action === "confirm") {
              goLogin(currentPath);
            }
          },
          beforeClose: () => {
            MessageBox.close();
          },
        });
      } else if (error.response.status === 403) {
        router.push({
          path: "/403",
        });
      } else if (error.response.status === 404) {
        router.push({
          path: "/404",
        });
      } else if (error.response.status === 500) {
        Message({
          message: "服务器内部发生错误，请与管理员联系",
          type: "error",
          duration: 5 * 1000,
        });
      }
      return Promise.reject(error);
    }
  }
);

export default service;
